package com.yulinlin.jdbc.mysql;

import com.yulinlin.core.wrapper.IParamsWrapper;
import com.yulinlin.core.wrapper.IStringConditionWrapper;
import com.yulinlin.core.wrapper.ITableWrapper;

import java.util.ArrayList;
import java.util.List;

public class MysqlTableWrapper<E,R> implements ITableWrapper<E,R> {

    private R  endWrapper;

    private IParamsWrapper params;


    private List<TableNode> tables;


    public MysqlTableWrapper(R endWrapper, IParamsWrapper params) {
        this.endWrapper = endWrapper;
        this.params = params;

        this.tables = new ArrayList<>();
    }




    @Override
    public ITableWrapper<E,R> table(String tableName) {
        TableNode node  =  new TableNode(tableName,null);
        this.tables.add(node);
        return this;
    }

    private IStringConditionWrapper<E,ITableWrapper<E,R>> join(String model, String tableName) {

        MysqlStringConditionWrapper wrapper =    new MysqlStringConditionWrapper<>(this,params);

        TableNode node  =  new TableNode(model +" join "+tableName,wrapper);

        this.tables.add(node);

        return wrapper;
    }

    @Override
    public IStringConditionWrapper<E, ITableWrapper<E, R>> left(String tableName) {
        return join("left",tableName);
    }

    @Override
    public IStringConditionWrapper<E, ITableWrapper<E, R>> right(String tableName) {
        return join("right",tableName);
    }

    @Override
    public IStringConditionWrapper<E, ITableWrapper<E, R>> inner(String tableName) {
        return join("inner",tableName);
    }

    @Override
    public R end() {

        return endWrapper;
    }

    @Override
    public String getSql() {

        StringBuffer sql =    new StringBuffer();

        for (TableNode node :tables){
            sql.append(" " + node.sql);
            if(node.on != null){
                String on =  node.on.getSql();
                sql.append(" on " + on);
            }

        }
        return sql.toString();
    }

    @Override
    public IParamsWrapper getParams() {
        return params;
    }


    private static class TableNode{

        String sql;

        IStringConditionWrapper on;

        public TableNode(String sql, IStringConditionWrapper on) {
            this.sql = sql;
            this.on = on;
        }
    }
}
